
import http from './request.js';

export const initMenu = (router,store)=>{

    if(store.state.routes.length>0){
        return;
    }

    http({
        method:"get",
        url:"/system/cfg/treeMenus",
    }).then(data=>{
        if(data && data.data){
            //格式化好的菜单列表
            let fmtRoutes = formatRoutes(data.data);
            //添加到router
            router.addRoutes(fmtRoutes);
            //将数据存入vuex
            store.commit("initRoutes",fmtRoutes);
            //开启websocket
            store.dispatch('chatConnect');
        }
    });
}

/**
 * 格式化菜单(路由)列表
 */
export const formatRoutes = routes=>{
    if(typeof routes == 'string'){
        routes = JSON.parse(routes);
    }
    let fmtRoutes = [];
    routes.forEach(router => {
        // console.log(router);
        let{path,component,name,icon,children} = router;
        if(children && children.length >0){
            children = formatRoutes(children);
        }
        let fmRouter = {
            path:path,
            name:name,
            icon:icon,
            children:children,
            component: resolve => {
                if(component.startsWith("Home")){
                    require([`@views/${component}.vue`],resolve);
                }else if(component.startsWith("Emp")){
                    require([`@views/emp/${component}.vue`],resolve);
                }else if(component.startsWith("Per")){
                    require([`@views/per/${component}.vue`],resolve);
                }else if(component.startsWith("Sal")){
                    require([`@views/sal/${component}.vue`],resolve);
                }else if(component.startsWith("Sta")){
                    require([`@views/sta/${component}.vue`],resolve);
                }else if(component.startsWith("Sys")){
                    require([`@views/sys/${component}.vue`],resolve);
                }
            } 
        }
        fmtRoutes.push(fmRouter);
    });

    return fmtRoutes;
}


